package indi.madoka.weeb.module.base.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import indi.madoka.weeb.bean.update.message.UpdateMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @author Arcueid
 */
@Service
@Slf4j
public class TraceMoeService {
    private final WebClient webClient;
    private static final String TRACE_MOE_API_URL = "https://api.trace.moe/search";
    private static final int RETURN_LIMIT = 5;

    public TraceMoeService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl(TRACE_MOE_API_URL).build();
    }

    public String getImageSource(UpdateMessage updateMessage) {
        String imageUrl = getUrlFromRawMessage(updateMessage);
        JSONObject resultJson = getApiResultByImageUri(imageUrl);
        JSONArray resultsInResult = resultJson.getJSONArray("result");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < (Math.min(resultsInResult.size(), RETURN_LIMIT)); i++) {
            sb.append("名称: ");
            String nativeName = resultsInResult.getJSONObject(i).getJSONObject("anilist")
                    .getJSONObject("title")
                    .getString("native");
            sb.append(nativeName);
            sb.append("\n相似度: " );
            String similarity = String.format( "%.2f",resultsInResult.getJSONObject(i).getDoubleValue("similarity") * 100);
            sb.append(similarity);
            sb.append("%\n");
        }
        return sb.toString();
    }

    private String getUrlFromMessage(UpdateMessage updateMessage) {
        return null;
    }

    private String getUrlFromRawMessage(UpdateMessage updateMessage) {
        String url = updateMessage.getRawMessage().split(",url=")[1];
        return url.replaceAll("]", "");
    }

    private JSONObject getApiResultByImageUri(String imageUri){
        return webClient.get()
                .uri("?anilistInfo&url=" + imageUri)
                .retrieve()
                .bodyToMono(JSONObject.class)
                .block();
    }
}
